﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using System.Data;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections.Generic;
using System.Web.UI;
using System.Linq;

namespace BIMP.ADMIN.BIMP
{
    public partial class ManageNotifications : LayoutsPageBase, IPostBackEventHandler
    {
        private DataTable NotificationsData = null;
        private string MenuScriptId = "NotificationsGridMenuScript";

        private Guid ListUID = Guid.Empty;
        private SPList TargetList = null;
        private SPSite TargetSite = null;
        private SPWeb  TargetWeb = null;

        private List<RmdConfiguration> AllListReminders;

        private string GetLocalizedString(string resourceKey)
        {
            return SPUtility.GetLocalizedString("$Resources:"+resourceKey, "BIMP", (uint)CultureInfo.CurrentUICulture.LCID);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            string strListId = Request.QueryString["ListID"].ToString();
            string strSiteUrl = Request.QueryString["SiteUrl"].ToString();
            ListUID = new Guid(strListId);

            TargetSite = new SPSite(strSiteUrl);
            TargetWeb = TargetSite.OpenWeb();

            TargetList = TargetWeb.Lists.GetList(ListUID, true);


            //string url =string.Format("/_layouts/BIMP/EditNotification.aspx?NotificationID=%TITLE%&amp;ListID={0}",strListId);
            string url = string.Format("/_admin/BIMP/EditNotification.aspx?NotificationID=%TITLE%&amp;ListID={0}&amp;SiteUrl={1}", strListId, Request.QueryString["SiteUrl"]);

            MenuItemTemplate1.ClientOnClickNavigateUrl = url;
            MenuItemTemplate2.ClientOnClickNavigateUrl = url;
            MenuItemTemplate3.ClientOnClickNavigateUrl = url;
            MenuItemTemplate4.ClientOnClickNavigateUrl = url;
            MenuItemDelete.ClientOnClickUsingPostBackEvent = "__page,DELETE,%TITLE%";
            MenuItemDelete.ClientOnClickPostBackConfirmation = "Are you sure you want to remove thie item ?";


            if (!Page.ClientScript.IsClientScriptBlockRegistered(MenuScriptId))
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), MenuScriptId, GridClientScript());
            }

            lblPageTitle.Text = GetLocalizedString("Page_ManageNotifications_PageTitle");
            lblPageTitleInTitleArea.Text = GetLocalizedString("Page_ManageNotifications_PageTitleInTitleArea");


            InitilizeGridData();
        
        }
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private void InitilizeGridData()
        {
            NotificationsData = new DataTable();

            NotificationsData.Columns.Add(new DataColumn("Title"));
            NotificationsData.Columns.Add(new DataColumn("Author"));
            NotificationsData.Columns.Add(new DataColumn("Created"));
            NotificationsData.Columns.Add(new DataColumn("LastRunTime"));
            NotificationsData.Columns.Add(new DataColumn("LastRunStatus"));
            NotificationsData.Columns.Add(new DataColumn("Guid"));


            AllListReminders = TargetList.ReadNotifications();

            if (AllListReminders == null)
                AllListReminders = new List<RmdConfiguration>();

            foreach (var n in AllListReminders)
            {

                BIMPJobDefinition jd = n.FindJobDefinition();


                DataRow row = NotificationsData.NewRow();

                row["Title"] = n.DisplayName;
                row["Author"] = n.AuthorID;
                row["Created"] = "";
                row["LastRunTime"] = jd == null ? "" : jd.LastRunTime.ToString();
                row["LastRunStatus"] = ((jd == null) || (jd.HistoryEntries.Count() == 0)) ? "Never Ever Started" : jd.HistoryEntries.First().Status.ToString();
                row["Guid"] = n.Id;

                NotificationsData.Rows.Add(row);
            }


            NotificationsGrid.DataSource = NotificationsData;
            NotificationsGrid.DataBind();
        }

        private string GridClientScript()
        {
            StringBuilder ClientCode = new StringBuilder();
            //GetColumnValue gets the value stored in the cell pointed by the columnindex
            ClientCode.Append("<script language='javascript'>");
            ClientCode.Append("function GetColumnValue(Target,ColumnIndex)");
            ClientCode.Append("{");
            ClientCode.Append("  if(Target){");
            ClientCode.Append("    if(Target.event.srcElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.tagName == 'TR')");
            ClientCode.Append("    {");
            ClientCode.Append("         return Target.event.srcElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.cells[ColumnIndex].innerText;");
            ClientCode.Append("    }else");
            ClientCode.Append("    {");
            ClientCode.Append("         return Target.event.srcElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.cells[ColumnIndex].innerText;");
            ClientCode.Append("    }");
            ClientCode.Append("  }");
            ClientCode.Append("}");
            //DisplayMenuItem returns true or false according to the value comparison.
            ClientCode.Append("function DisplayMenuItem(Target,ColumnIndex,ValueToCompare)");
            ClientCode.Append("{");
            ClientCode.Append("   if(GetColumnValue(Target,ColumnIndex) != ValueToCompare)");
            ClientCode.Append("             return true;");
            ClientCode.Append("         else");
            ClientCode.Append("             return false;");
            ClientCode.Append("}");
            ClientCode.Append("</script>");
            return ClientCode.ToString();
        }

        protected void SortGrid(object sender, GridViewSortEventArgs e)
        {
            DataTable ColumnInfo = NotificationsGrid.DataSource as DataTable;
            if (ColumnInfo != null)
            {
                DataView ColumnView = new DataView(ColumnInfo);
                string lastExpression = "";
                if (ViewState["SortExpression"] != null)
                    lastExpression = ViewState["SortExpression"].ToString();

                string lastDirection = "asc";
                if (ViewState["SortDirection"] != null)
                    lastDirection = ViewState["SortDirection"].ToString();

                string newDirection = "asc";
                if (e.SortExpression == lastExpression)
                    newDirection = (lastDirection == "asc") ? "desc" : "asc";

                ViewState["SortExpression"] = e.SortExpression;
                ViewState["SortDirection"] = newDirection;
                ColumnView.Sort = e.SortExpression + " " + newDirection;
                NotificationsGrid.DataSource = ColumnView;
                NotificationsGrid.DataBind();
            }

        }

        public void RaisePostBackEvent(string eventArgument)
        {
            string[] splits = eventArgument.Split(',');
            string cmd = splits[0];
            
            if (cmd == "DELETE")
                DeleteNotification(new Guid(splits[1]));
        }

        private void DeleteNotification(Guid NotificationUID)
        {
            if (AllListReminders == null || AllListReminders.Count == 0)
                return;

            TargetList.RemoveNotification(NotificationUID);

            InitilizeGridData();
        }
    }
}
